package com.yfkj.sms.mongodb.service.impl;

import com.mongodb.BasicDBObject;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.yfkj.sms.mongodb.service.YfkjSmsMongoService;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @ClassName YfkjSmsMongoServiceImpl
 * @Description TODO
 * @Author mzb
 * @Version V1.0.0
 */
@DubboService
public class YfkjSmsMongoServiceImpl implements YfkjSmsMongoService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * @param object, col]
     * @return void
     * @author mzb
     * @description 插入数据
     **/
    @Override
    public void insertObjectToCol(Object object, String col) {
        mongoTemplate.insert(object, col);
    }

    @Override
    public void insert(List<Object> list, String col) {
        mongoTemplate.insert(list, col);
    }
    /**
     * @param tClass 类
     * @param col    集合名
     * @return java.util.List<T>
     * @author mzb
     * @description 查询集合
     **/
    @Override
    public <T> List<T> findAll(Class<T> tClass, String col) {
        return mongoTemplate.findAll(tClass, col);
    }

    /**
     * @param col       集合名
     * @param tClass    clz
     * @param pageIndex 页数
     * @param pageSize  条数
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author mzb
     * @description 分页查询
     **/
    @Override
    public <T> Map<String, Object> findAllByPage(String col, Class<T> tClass, int pageIndex, int pageSize) {
        Query query = new Query();

        Map<String, Object> map = new HashMap<String, Object>(2);
        query.limit(pageSize).skip(pageSize * (pageIndex - 1));
        long count = mongoTemplate.getCollection(col).estimatedDocumentCount();
        List<T> data = mongoTemplate.find(query, tClass, col);
        map.put("count", count);
        map.put("data", data);
        return map;
    }

    @Override
    public long deleteMany(String col, String jsonOp) {
        BasicDBObject parse = BasicDBObject.parse(jsonOp);
        DeleteResult deleteResult = mongoTemplate.getCollection(col).deleteMany(parse);
        return deleteResult.getDeletedCount();
    }


}
